<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Static Template</title>
    <style>
        @keyframes show {
            0% {
                opacity: .5;
                transform: translateY(-30px);
            }

            100% {
                opacity: 1;
                transform: translateY(0px);
            }
        }

        body {
            animation: show .5s ease;
            background-color: lightslategrey;
        }

        .wrapper {
            width: 35vw;
            height: 35vw;
            margin: 50px auto;
        }

        .container {
            width: 100%;
            height: 100%;
            border-radius: 15px;
            position: relative;

            /* border: solid 1px red; */
        }

        .cell {
            font-size: 50px;
            position: absolute;
            width: 120px;
            height: 120px;
            line-height: 120px;
            text-align: center;
            background: #eee;
            border-radius: 15px;
            font-weight: 999;
            color: lightslategrey;
            transition: all .3s ease;
            cursor: pointer;
        }

        .cell:hover {
            box-shadow: 0 0 20px rgba(65, 64, 64, 0.5);
        }

        .clock {
            position: absolute;
            right: 20%;
            top: 30%;
            font-weight: bolder;
            color: #fff;
            font-size: 30px;
        }

        .his {
            position: absolute;
            left: 5%;
            top: 30%;
            font-weight: bolder;
            color: #fff;
            font-size: 30px;
        }
    </style>
</head>

<body>
    <div class="wrapper">
        <div class="container"></div>
        <p style="text-align: center;cursor: pointer;font-size: 20px;color:#fff;font-weight: bold;" onclick="start()">
            START</p>
        <p class="clock">0 s</p>
        <p class="his">历史最佳：0 s</p>
    </div>
    <script src="../util.js"></script>
    <script>

        const his_score = document.querySelector(".his");
        let user = storage.get("user");
        console.log(user)
        his_score.innerHTML = `历史最佳：${user.score ?? 0}`;

        // 计时
        const clock = document.querySelector(".clock");
        let time = 0;
        let flag = false;
        let startClock = () => {
            if (!flag) {
                time = 0;
                clock.innerHTML = "0 s";
                return;
            };
            setTimeout(() => {
                time++;
                clock.innerHTML = time + "s";
                startClock();
            }, 1000)
        }
        // 检查获胜
        let checkwin = arr => {
            let flag = true;
            arr.forEach((item, i1) => {
                ["1", "2", "3", "4", "5", "6", "7", "8", "white"].forEach((it, i2) => {
                    if (i1 === i2 && item !== it) {
                        flag = false;
                    }
                })
            });
            return flag;
        }

        const container = document.querySelector(".container");
        // cell count
        const cellCount = 9;
        // space width
        const whiteSpace = 5;
        // line count
        const rowCount = Math.sqrt(9);
        // container width;
        const containerWidth = container.offsetWidth;
        //row height/width
        const rowWidth = containerWidth / rowCount - whiteSpace * 2;
        // cell pos array
        const posRecord = [];
        // add cell
        for (let i = 0; i < cellCount - 1; i++) {
            posRecord.push(i + 1 + "");
        }
        posRecord.push("white");
        function getPos(i) {
            const row = Math.floor(i / rowCount);
            const col = i % rowCount;
            const top = whiteSpace + (rowWidth + whiteSpace * 2) * row + "px";
            const left = whiteSpace + (rowWidth + whiteSpace * 2) * col + "px";
            return { top, left };
        }
        function canMove(cell) {
            const whiteIndex = posRecord.indexOf("white");
            const currIndex = posRecord.indexOf(cell.innerText);

            const whiteRow = Math.floor(whiteIndex / rowCount);
            const currRow = Math.floor(currIndex / rowCount);
            const whiteCol = whiteIndex % rowCount;
            const currCol = currIndex % rowCount;
            return (
                (whiteRow == currRow && ((currCol + 1 == whiteCol) || (currCol - 1 == whiteCol))) ||
                (whiteCol == currCol && ((currRow + 1 == whiteRow) || (currRow - 1 == whiteRow)))
            );
        }
        function move(cell) {
            if (!canMove(cell) || !flag) return;
            const whiteIndex = posRecord.indexOf("white");
            const currIndex = posRecord.indexOf(cell.innerText);
            const pos = getPos(whiteIndex);
            cell.style.top = pos.top;
            cell.style.left = pos.left;
            posRecord[whiteIndex] = cell.innerText;
            posRecord[currIndex] = "white";
            const isWin = checkwin(posRecord);
            if (isWin) {
                setTimeout(() => {
                    flag = false;
                    alert("成功了！共耗时" + time + "秒");
                    // const user = storage.get("user");

                    if (time < (user.score ?? 0) || user.score === undefined) {
                        user.score = time;
                        storage.set("user", user);
                        const usersAnduser = userDB.updateOne(user.username, user);
                        his_score.innerHTML = `历史最佳：${time} s`;
                    }
                    clock.innerHTML = "0 s";
                    time = 0;
                }, 500)
            }
        }
        for (let i = 0; i < posRecord.length; i++) {
            if (posRecord[i] === "white") continue;
            const cell = document.createElement("div");
            cell.className = "cell";
            cell.style.lineHeight = rowWidth + "px";
            cell.style.width = rowWidth + "px";
            cell.style.height = rowWidth + "px";
            const pos = getPos(i);
            cell.style.top = pos.top;
            cell.style.left = pos.left;
            cell.innerText = posRecord[i];
            cell.onclick = function () {
                move(this);
            };
            container.appendChild(cell);
        }

        // 打乱顺序
        function start() {
            if (flag) return;
            // 开始计时
            flag = true;
            startClock();
            const cells = document.querySelectorAll(".cell");
            for (let i = 0; i < 200; i++) {
                cells.forEach(cell => {
                    cell.onclick();
                })
            }
        }

        ["1", "2", "3", "4", "5", "6", "7", "white", "8"]
    </script>


</body>

</html>